<template>
  <div class="code-editor-container">
    <el-input
      v-model="code"
      :id="id" type="textarea"
      :autosize="{minRows: 10}">
    </el-input>
  </div>
</template>

<script>
  import CodeMirror from 'codemirror';
  import 'codemirror/lib/codemirror.css';
  import 'codemirror/mode/javascript/javascript';
  import 'codemirror/theme/midnight.css';
  import 'codemirror/addon/lint/json-lint';
  import 'codemirror/addon/selection/active-line.js';

  export default {
    name: 'CodeEditor',
    model: {
      prop: 'funcCode',
      event: 'change'
    },
    props: {
      id: {
        type: String,
        default: 'codeTextarea'
      },
      mode: {
        type: String,
        default: 'javascript'
      },
      funcCode: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        code: '',
        codeEditor: null,
      };
    },
    watch: {
      funcCode: {
        handler(val = '') {
          this.code = val;
        },
        immediate: true
      }
    },
    mounted() {
      this.initCodeEditor();
    },
    methods: {
      initCodeEditor() {
        const codeTextarea = document.getElementById(this.id);
        this.codeEditor = CodeMirror.fromTextArea(codeTextarea, {
          lineNumbers: true,
          mode: this.mode,  // 设置mode
          indentUnit: 2,  // 默认为2
          tabSize: 2,  // 默认为4
          lineWrapping: true,  // 代码过长换行
          styleActiveLine: true,
          theme: 'midnight',
          lint: true,
        });
        this.codeEditor.on('change', (cm, change) => {
          this.$emit('change', this.codeEditor.getValue());
        });
        this.codeEditor.setSize("100%", 'auto');
        this.codeEditor.setValue(this.code || '');
      }
    },
  };
</script>

<style scoped lang="less">

</style>
